package chuangyi.com.org.ViewModel;

import android.app.Activity;
import android.content.Context;
import android.databinding.Bindable;
import android.view.View;
import android.widget.CalendarView;
import android.widget.Toast;

import com.solidfire.gson.internal.LinkedTreeMap;
import com.umeng.socialize.ShareContent;
import com.umeng.socialize.media.UMImage;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import chuangyi.com.org.DOMIHome.BR;
import chuangyi.com.org.DOMIHome.Fragments.CommonFragment;
import chuangyi.com.org.DOMIHome.HomeActivity;
import chuangyi.com.org.DOMIHome.LoadingDialog;
import chuangyi.com.org.DOMIHome.PopupActivity;
import chuangyi.com.org.DOMIHome.R;
import chuangyi.com.org.DOMIHome.Utils.Utils;
import chuangyi.com.org.DOMIHome.Utils.WebApi;
import chuangyi.com.org.DOMIHome.adapter.ListBindingAdapter;
import chuangyi.com.org.DOMIHome.adapter.XListAdapterInterface;
import chuangyi.com.org.DOMIHome.adapter.XListBindingAdapter;

/**
 * Created by zxh on 16/12/6.
 */

public class RewardDetail extends XListModel {
    private QuestionItem question;
    private int answerCount;
    private boolean listViewMode;
    private ListBindingAdapter<ParagraphItem> paragraphs;

    @Bindable
    public ListBindingAdapter<ParagraphItem> getParagraphs() {
        return paragraphs;
    }

    @Bindable
    public boolean isListViewMode() {
        return listViewMode;
    }

    public void setListViewMode(boolean listViewMode) {
        this.listViewMode = listViewMode;
        notifyPropertyChanged(BR.listViewMode);
    }

    @Bindable
    public boolean getAllowJoin() {
        return question.getUid() != User.getCurrentUser().getUid();
    }

    @Bindable
    public QuestionItem getQuestion() {
        return question;
    }

    public void setQuestion(QuestionItem question) {
        this.question = question;
    }

    @Bindable
    public int getAnswerCount() {
        return answerCount;
    }

    public void setAnswerCount(int answerCount) {
        this.answerCount = answerCount;
        notifyPropertyChanged(BR.answerCount);
    }

    public RewardDetail(Context context) {
        super(context);
        listViewMode = true;
    }

    public void onClickLabel(View view) {
        setListViewMode(!listViewMode);
    }

    /**
     * 点击参与悬赏
     *
     * @param view
     */
    public void onClickJoinReward(View view) {
        if (question.getUid() == User.getCurrentUser().getUid()) {
            showToast("不能参与自己发布的悬赏");
            return;
        }
        LoadingDialog.getInstance(getContext()).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!WebApi.allowAction(getContext())) {
                    LoadingDialog.getInstance(getContext()).dismiss();
                    return;
                }
                if (WebApi.partakecheck(getContext(), getQuestion().getId())) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            JoinReward reward = new JoinReward(getContext());
                            reward.setQuestion(question);
                            CommonFragment fragment = new CommonFragment();
                            fragment.setVariableId(BR.reward);
                            fragment.setDataModel(reward);
                            fragment.setLayoutId(R.layout.a_join_xuanshang);
                            HomeActivity.switchFragment((Activity) getContext(), fragment);
                        }
                    });
                } else {

                }
                LoadingDialog.getInstance(getContext()).dismiss();
            }
        }).start();
    }

    /**
     * 点击发布新悬赏
     *
     * @param view
     */
    public void onClickPublishReward(View view) {
        EditReward reward = new EditReward(getContext());
        CommonFragment fragment = new CommonFragment();
        fragment.setVariableId(BR.editor);
        fragment.setDataModel(reward);
        fragment.setLayoutId(R.layout.f_send_xuanshang);
        HomeActivity.switchFragment((Activity) getContext(), fragment);
    }

    @Override
    public void load(final int page) {
        getAdapter().clear(true);
        setNoMore();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final XListAdapterInterface adapter = getAdapter();
                    LinkedTreeMap map = WebApi.getRewardDetail(getContext(), question.getId());
                    if (map == null)
                        return;
                    question.setUid(Utils.getIntValue(map.get("uid")));
                    question.setMoney(Utils.getDoubleValue(map.get("money")));
                    question.setLefttime(Utils.getIntValue(map.get("lefttime")));
                    int status = Utils.getIntValue(map.get("status"));
                    switch (status) {
                        case 0:
                            question.setLefttime(-1);
                            break;
                        case 2:
                            question.setLefttime(0);
                            break;
                    }
                    question.startTimer();
                    question.setTitle((String) map.get("title"));
                    question.setAvatar((String) map.get("avatar"));
                    question.setNickname((String) map.get("nickname"));
                    question.setLabel((String) map.get("label"));
                    question.setJob((String) map.get("job"));
                    question.setDesc((String) map.get("questiondesc"));
                    question.setStartdate(Utils.getDateFromFormat(map.get("startdate"), "yyyy-MM-dd HH:mm:ss"));
                    question.setInnerSystime((String) map.get("systime"));

                    setAnswerCount(Utils.getIntValue(map.get("answercoun")));
                    final ArrayList list = (ArrayList) map.get("list");
                    adapter.setVariableId(BR.answer);
                    int rank = 0;
                    for (Object item : list) {
                        AnswerItem answerItem = new AnswerItem(getContext(), R.layout.i_answer_item,
                                RewardDetail.this.question);
                        LinkedTreeMap answerMap = (LinkedTreeMap) item;
                        answerItem.setShowMoney(question.getMoney() > 0);
                        answerItem.setRankRes(rank);
                        answerItem.setUid(Utils.getIntValue(answerMap.get("uid")));
                        answerItem.setAvatar((String) answerMap.get("avatar"));
                        answerItem.setAnswerId(Utils.getIntValue(answerMap.get("respondid")));
                        answerItem.setNickName((String) answerMap.get("nickname"));
                        answerItem.setAnswerTime(Utils.getDateFromFormat(answerMap.get("respondtime"), "yyyy-MM-dd HH:mm:ss"));
                        answerItem.setContent((String) answerMap.get("respondcontent"));
                        answerItem.setLikeCount(Utils.getIntValue(answerMap.get("likecoun")));
                        answerItem.setJob((String) answerMap.get("job"));
                        answerItem.setRewardAmount(Utils.getDoubleValue(answerMap.get("money")));
                        answerItem.setParent(RewardDetail.this);
                        adapter.add(answerItem);
                        rank++;
                    }
                    if (list.size() != 0) {
                        setCurrentPage(page);
                    }
                    notifyDataSetChanged(list);
                } catch (Exception ex) {
                    showToast("解析数据时发生错误");
                }

            }
        }).start();
    }

    public void loadParagraphs() {
        if (paragraphs == null) {
            List<Integer> viewTypes = new ArrayList<Integer>();
            viewTypes.add(R.layout.i_text_paragraph);
            viewTypes.add(R.layout.i_image_paragraph);
            paragraphs = new ListBindingAdapter<ParagraphItem>(getContext(), BR.paragraph, viewTypes);
            notifyPropertyChanged(BR.paragraphs);
        } else {
            paragraphs.clear(true);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList list = WebApi.rewardParagraphDetail(getContext(), question.getId());
                for (Object item : list) {
                    LinkedTreeMap inner = (LinkedTreeMap) item;
                    int contentType = Utils.getIntValue(inner.get("contenttype"));
                    ParagraphItem paragraph = new ParagraphItem(getContext(), contentType);
                    paragraph.setContent((String) inner.get("content"));
                    paragraph.setAllowEdit(false);
                    paragraphs.add(paragraph);
                }
                notifyDataSetChanged(paragraphs);
            }
        }).start();
    }

    /**
     * 点击打开悬赏二级详情页
     *
     * @param view
     */
    public void onClickTitle(View view) {
        this.loadParagraphs();
        CommonFragment fragment = new CommonFragment();
        fragment.setDataModel(this);
        fragment.setLayoutId(R.layout.f_reward_detail);
        fragment.setVariableId(BR.detail);
        HomeActivity.switchFragment((Activity) getContext(), fragment);
    }

    public void onClickShare(View view) {
        Activity activity = (Activity) getContext();
        ShareModel model = new ShareModel(activity);
        model.setShareType("reward");
        model.setId(getQuestion().getId());
        model.setShareCallback(new ShareModel.Callback() {
            @Override
            public void onShareSuccess() {
            }

            @Override
            public void onShare(ShareItem shareItem) {
                ShareContent content = new ShareContent();
                content.mTitle = ShareModel.SHARE_TITLE;
                content.mText = ShareModel.SHARE_TEXT;
                content.mMedia = new UMImage(getContext(), ShareModel.SHARE_IMG);
                content.mTargetUrl = WebApi.getShareUrl();
                shareItem.setShareData(content);
            }
        });
        PopupActivity.startActivity(activity, R.layout.v_dialog_share, BR.share, model);
    }
}
